package com.example.demo.filter;
import com.alibaba.fastjson.JSON;
import com.example.demo.common.BaseContext;
import com.example.demo.common.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.servlet.AntPathRequestMatcherProvider;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
        };
        BaseContext.SteCurrentId((Long) request.getSession().getAttribute("employee"));
        //1、判断路径和已登录
        if(FilterUrl(urls,request.getRequestURI()) || request.getSession().getAttribute("employee") != null){
            filterChain.doFilter(request,response);
        }else {
            //2、未登录路径不匹配
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }



    }

    /**
     * 判读url
     * @param urls
     * @param requestUrl
     * @return
     */
    public static boolean FilterUrl(String[] urls,String requestUrl){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match){
                return true;
            }
        }
        return false;
    }
}
